package com.xia.netty.proxy;

import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class ProxyDemo {

    public static void main(String[] args) {
        //创建被代理的对象
        BaoQiang baoQiang = new BaoQiang();
        //创建代理对象
        //获取类的加载器
        ClassLoader classLoader = baoQiang.getClass().getClassLoader();

        //获取被代理的接口
        Class<?>[] interfaces = baoQiang.getClass().getInterfaces();
        //定义调用处理器
        InvocationHandler handler = new MyInvocationHandle(baoQiang);
        Object o = Proxy.newProxyInstance(classLoader, interfaces, handler);

        Star star = (Star)o;
        double v = star.liveShow(100);
        System.out.println("money: "+ v);
        star.sleep("100");


    }


    private static class MyInvocationHandle implements InvocationHandler {
        private final BaoQiang baoQiang;

        /**
         * 代理对象调用的方法主要实现逻辑
         * @param proxy 被代理的对象
         * @param method 调用的方法
         * @param args 方法的参数列表
         * @return
         * @throws Throwable
         */
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            String name = method.getName();
           System.out.println("调用的方法名称是: " + name + ",参数为:"+ Arrays.toString(args));

            if (StringUtils.equals(name, "liveShow")){
                double m = (double)args[0];
                System.out.println("宋哲佣金:"+ m*0.4);
                Object result = method.invoke(baoQiang, m);
                System.out.println("宋哲帮宝强存了"+ result + "到银行") ;
                return result;
            }

            Object invoke = method.invoke(baoQiang, args);
            System.out.println(invoke);
            return invoke;
        }

        public MyInvocationHandle(BaoQiang baoQiang) {
            this.baoQiang= baoQiang;
        }
    }
}
